import { AudioClip, AudioSource, director, Node, resources } from 'cc';
import Instance from '../utils/Instance';

export class AudioMgr {
    public static getInstance(): AudioMgr {
        return Instance.get<AudioMgr>(AudioMgr);
    }

    private audioMgr: Node;
    private audioS: AudioSource;
    private volume: number;
    private soundOn: boolean;

    constructor() {
        //创建一个节点
        const audioMgr = new Node();
        audioMgr.name = '__audioMgr__';

        //节点添加到当前场景
        director.getScene().addChild(audioMgr);

        //标记为常驻场景
        director.addPersistRootNode(audioMgr);

        //添加音频组件
        this.audioS = audioMgr.addComponent(AudioSource);

        //监听音频播放
        this.audioS.node.on(AudioSource.EventType.STARTED, this.onAudioStarted, this);
        this.audioS.node.on(AudioSource.EventType.ENDED, this.onAudioEnded, this);

        this.volume = 0.5;

        this.soundOn = false;
    }

    public get audioSource() {
        return this.audioS;
    }

    playOneShot(sound: AudioClip | string, volume?: number) {
        volume && (this.volume = volume);
        if (sound instanceof AudioClip) {
            this.audioS.playOneShot(sound, this.volume);
        } else {
            resources.load(sound, AudioClip, (err, clip) => {
                if (err) {
                    console.log('load audio clip failed!');
                    return;
                }
                this.audioS.playOneShot(clip, this.volume);
            });
        }
    }

    play(sound: AudioClip | string, volume?: number) {
        volume && (this.volume = volume);
        if (sound instanceof AudioClip) {
            this.audioS.stop(); //先停止正常播放的音乐
            this.audioS.clip = sound;
            this.audioS.play();
            this.audioS.volume = this.volume;
        } else {
            resources.load(sound, AudioClip, (err, clip) => {
                if (err) {
                    console.log('load audio clip failed!');
                    return;
                }
                this.audioS.stop();
                this.audioS.clip = clip;
                this.audioS.play();
                this.audioS.volume = this.volume;
            });
        }
    }

    pause() {
        this.audioS.pause();
    }

    resume() {
        this.audioS.play();
    }

    stop() {
        this.audioS.stop();
    }

    onAudioStarted() {
        this.soundOn = true;
    }

    onAudioEnded() {
        this.soundOn = false;
    }

    destroy() {
        this.stop();
        this.audioS.node.off(AudioSource.EventType.STARTED, this.onAudioStarted, this);
        this.audioS.node.off(AudioSource.EventType.ENDED, this.onAudioEnded, this);
        this.audioS.node.destroy();
    }
}
